function [IDLE, TX, BO, CS, error]=solveNode(p,vPi,vP,maxBOs,CW)
%
%    Function to solve the embeded Markov Chain steady-state probability valance equations that
%  describes the Contention Acces Period (CAP) of a Node using IEEE 802.15.4
%
%    Inputs:
%      -p:      probability to begin transmission
%      -vPi_:   contitional probability that the channel is iddle durin 'ind' given that has been idle during 'ind-1' (_ removed)
%      -vP:     probability transitions related to B0x, random backoff before channel sensing
%      -maxBOs: maximum permited Backoffs Stages BOx (macMaxCSMABackoffs)
%      -CW:     Contention Window
%
%    Outputs: 
%      -IDLE:   long term proportion of transitions into state Idle
%      -TX:     long term proportion of transitions into state Tx
%      -BO:     long term proportion of transitions into state BO
%      -CS:     long term proportion of transitions into state CS
%      -error:  one state has prob < 0 or > 1
%
%  Joaquín Recas-Piorno, December 2013
%  recas@ucm.es
%

  ind_Idle=maxBOs*(CW+1)+1;
  ind_tx=ind_Idle+1;

  A=[];
  
  %IDLE equation Eq(A.1)
  A(end+1,ind_Idle)=p;
  A(end,ind_tx)=-1;
  for i=1:CW
    A(end,maxBOs*(i+1))=-(1-vPi(i));
  end

  %BO1 equation Eq(A.2)
  A(end+1,1)=vP(1);
  A(end,ind_Idle)=-p*(1-vP(1));
  for i=2:maxBOs
    %BOx equation Eq(A.3)
    A(end+1,i)=vP(i);
    for j=1:CW
      A(end,maxBOs*j-1+i)=-(1-vPi(j))*(1-vP(i));
    end
  end

  %CS1 equation Eq(A.3)
  A(end+1,1)=-vP(1);
  A(end,maxBOs+1)=1;
  A(end,ind_Idle)=-p*vP(1);
  for i=2:maxBOs
    %CSj,1 equation Eq(A.5)
    A(end+1,i)=-vP(i);
    A(end,maxBOs+i-1)=-vP(i)*(1-vPi(1));
    A(end,maxBOs+i)=1;
    for j=2:CW
      A(end,maxBOs*j+i-1)=-vP(i)*(1-vPi(j));
    end
  end

  %CSj,k equation Eq(A.6)
  for i=1:CW-1
    for j=1:maxBOs
      A(end+1,maxBOs*i+j)=-vPi(i);
      A(end,maxBOs*(i+1)+j)=1;
    end
  end

  %Valance equation Eq(A.7)
  A(end+1,:)=ones(1,maxBOs*(CW+1)+2);
  
  % Solve it using [0...0, 1] as the indpendient value
  %x=inv(A)*[zeros(1,1+maxBOs*(CW+1)),1]';
  x=A\[zeros(1,1+maxBOs*(CW+1)),1]';

  if(max(x)>1||min(x)<0)
    error=1;
  else
    error=0;
  end

  IDLE=x(ind_Idle);
  TX=x(ind_tx);
  BO=x(1:maxBOs)';
  CS=reshape(x(maxBOs+1:end-2),maxBOs,CW)';

end
